<!DOCTYPE html>
<html
  xmlns:th="http://www.thymeleaf.org"
  xmlns:sec="http://www.thymeleaf.org/extras/spring-security"
>
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>AI面试对话 - AI面试系统</title>
    <link
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css"
      rel="stylesheet"
    />
    <link
      rel="stylesheet"
      href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css"
    />
    <style>
      .chat-container {
        height: 70vh;
        overflow-y: auto;
        border: 1px solid #dee2e6;
        border-radius: 0.375rem;
        padding: 1rem;
        background-color: #f8f9fa;
      }
      .message {
        margin-bottom: 1rem;
        display: flex;
        align-items: flex-start;
      }
      .message.user {
        justify-content: flex-end;
      }
      .message.ai {
        justify-content: flex-start;
      }
      .message-content {
        max-width: 70%;
        padding: 0.75rem 1rem;
        border-radius: 1rem;
        word-wrap: break-word;
      }
      .message.user .message-content {
        background-color: #007bff;
        color: white;
      }
      .message.ai .message-content {
        background-color: white;
        border: 1px solid #dee2e6;
      }
      .message-avatar {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 0 0.5rem;
        font-size: 1.2rem;
      }
      .message.user .message-avatar {
        background-color: #007bff;
        color: white;
      }
      .message.ai .message-avatar {
        background-color: #28a745;
        color: white;
      }
      .typing-indicator {
        display: none;
        align-items: center;
        margin-bottom: 1rem;
      }
      .typing-dots {
        display: flex;
        gap: 0.25rem;
      }
      .typing-dots span {
        width: 8px;
        height: 8px;
        border-radius: 50%;
        background-color: #6c757d;
        animation: typing 1.4s infinite ease-in-out;
      }
      .typing-dots span:nth-child(1) {
        animation-delay: -0.32s;
      }
      .typing-dots span:nth-child(2) {
        animation-delay: -0.16s;
      }
      @keyframes typing {
        0%,
        80%,
        100% {
          transform: scale(0);
        }
        40% {
          transform: scale(1);
        }
      }
      .resume-summary {
        background-color: #e3f2fd;
        border-left: 4px solid #2196f3;
        padding: 1rem;
        margin-bottom: 1rem;
        border-radius: 0.375rem;
      }
    </style>
  </head>
  <body>
    <nav
      class="navbar navbar-expand-lg navbar-dark"
      style="
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
      "
    >
      <div class="container">
        <a class="navbar-brand d-flex align-items-center" href="#">
          <i class="bi bi-robot me-2" style="font-size: 1.5rem"></i>
          AI面试系统
        </a>
        <button
          class="navbar-toggler border-0"
          type="button"
          data-bs-toggle="collapse"
          data-bs-target="#navbarNav"
        >
          <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarNav">
          <ul class="navbar-nav ms-auto">
            <li class="nav-item">
              <span class="nav-link d-flex align-items-center">
                <i class="bi bi-person-circle me-2"></i>
                欢迎，[[${#authentication?.principal?.username ?: '游客'}]]
              </span>
            </li>
            <li class="nav-item">
              <a
                class="nav-link d-flex align-items-center"
                th:href="@{/interviews}"
              >
                <i class="bi bi-list-ul me-2"></i>我的面试
              </a>
            </li>
            <li class="nav-item" sec:authorize="hasRole('ADMIN')">
              <a
                class="nav-link d-flex align-items-center"
                th:href="@{/admin/users}"
              >
                <i class="bi bi-people me-2"></i>用户管理
              </a>
            </li>
            <li class="nav-item">
              <a
                class="nav-link d-flex align-items-center"
                th:href="@{/logout}"
              >
                <i class="bi bi-box-arrow-right me-2"></i>退出登录
              </a>
            </li>
          </ul>
        </div>
      </div>
    </nav>

    <div class="container mt-4">
      <div class="row">
        <div class="col-12">
          <div
            class="card shadow-lg border-0"
            style="border-radius: 20px; overflow: hidden"
          >
            <div
              class="card-header text-white d-flex justify-content-between align-items-center"
              style="
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                border: none;
              "
            >
              <div class="d-flex align-items-center">
                <i class="bi bi-chat-dots me-3" style="font-size: 1.5rem"></i>
                <div>
                  <h4 class="mb-1">AI面试对话</h4>
                  <p class="mb-0 opacity-75">与AI面试官实时对话</p>
                </div>
              </div>
              <div class="d-flex gap-2">
                <span
                  class="badge bg-light text-dark px-3 py-2"
                  th:text="${interview != null && interview.jobPosition != null ? '职位: ' + interview.jobPosition : '职位信息不可用'}"
                  style="border-radius: 15px"
                >
                </span>
                <span
                  class="badge bg-warning text-dark px-3 py-2"
                  th:text="${interview != null ? '问题 ' + (interview.currentQuestionNumber != null ? interview.currentQuestionNumber : 1) + '/' + (interview.totalQuestions != null ? interview.totalQuestions : 5) : '问题信息不可用'}"
                  style="border-radius: 15px"
                >
                </span>
              </div>
            </div>
            <div class="card-body">
              <!-- 简历概括 -->
              <div
                th:if="${interview != null && interview.resumeSummary != null}"
                class="resume-summary mb-4"
              >
                <div class="d-flex align-items-start">
                  <div class="bg-primary bg-opacity-10 rounded-circle p-2 me-3">
                    <i class="bi bi-file-text text-primary"></i>
                  </div>
                  <div>
                    <h6 class="text-primary mb-2">
                      <i class="bi bi-file-text me-2"></i> 简历概括
                    </h6>
                    <p
                      th:text="${interview.resumeSummary}"
                      class="mb-0 text-muted"
                    ></p>
                  </div>
                </div>
              </div>

              <!-- 聊天消息区域 -->
              <div id="chatContainer" class="chat-container">
                <!-- 消息将通过JavaScript动态添加 -->
              </div>

              <!-- 输入区域 -->
              <div class="mt-4">
                <div class="card border-0 shadow-sm">
                  <div class="card-body p-4">
                    <div class="input-group">
                      <textarea
                        id="messageInput"
                        class="form-control border-0 shadow-none"
                        rows="3"
                        placeholder="请输入您的回答..."
                        th:disabled="${interview != null && interview.status != null && interview.status.name() == 'COMPLETED'}"
                        style="border-radius: 15px; resize: none"
                      ></textarea>
                      <button
                        id="sendButton"
                        class="btn btn-primary ms-2"
                        type="button"
                        th:disabled="${interview != null && interview.status != null && interview.status.name() == 'COMPLETED'}"
                        style="border-radius: 15px; min-width: 100px"
                      >
                        <i class="bi bi-send me-2"></i> 发送
                      </button>
                    </div>
                    <div class="form-text mt-2">
                      <span
                        th:if="${interview != null && interview.status != null && interview.status.name() == 'IN_PROGRESS'}"
                        class="d-flex align-items-center"
                      >
                        <i class="bi bi-info-circle me-2"></i>
                        请回答AI的问题，回答完成后点击发送按钮
                      </span>
                      <span
                        th:if="${interview != null && interview.status != null && interview.status.name() == 'COMPLETED'}"
                        class="text-success d-flex align-items-center"
                      >
                        <i class="bi bi-check-circle me-2"></i> 面试已完成
                      </span>
                    </div>
                  </div>
                </div>
              </div>

              <!-- 操作按钮 -->
              <div class="mt-4 text-center">
                <a
                  th:href="@{/interview}"
                  class="btn btn-outline-secondary me-3"
                  style="border-radius: 15px"
                >
                  <i class="bi bi-arrow-left me-2"></i> 返回
                </a>
                <a
                  th:if="${interview != null && interview.status != null && interview.status.name() == 'COMPLETED'}"
                  th:href="@{/result/{id}(id=${interview.id})}"
                  class="btn btn-success"
                  style="border-radius: 15px"
                >
                  <i class="bi bi-clipboard-check me-2"></i> 查看结果
                </a>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 打字指示器 -->
    <div id="typingIndicator" class="typing-indicator">
      <div class="message-avatar">
        <i class="bi bi-robot"></i>
      </div>
      <div class="typing-dots">
        <span></span>
        <span></span>
        <span></span>
      </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
    <script th:inline="javascript">
      const interviewId =
        /*[[${interview != null && interview.id != null ? interview.id : null}]]*/ null;
      const chatContainer = document.getElementById("chatContainer");
      const messageInput = document.getElementById("messageInput");
      const sendButton = document.getElementById("sendButton");
      const typingIndicator = document.getElementById("typingIndicator");

      // 调试信息
      console.log("Interview ID:", interviewId);
      console.log(
        "Interview object:",
        /*[[${interview != null ? interview : 'null'}]]*/ null
      );

      // 检查interviewId是否有效
      if (!interviewId) {
        console.error("Interview ID is null or undefined!");
        document.body.innerHTML =
          '<div class="container mt-5"><div class="alert alert-danger">错误：面试ID无效，请重新开始面试。</div><a href="/interview" class="btn btn-primary">返回面试页面</a></div>';
      }

      // 页面加载时获取聊天历史
      document.addEventListener("DOMContentLoaded", function () {
        loadChatHistory();
      });

      // 发送消息
      sendButton.addEventListener("click", sendMessage);
      messageInput.addEventListener("keypress", function (e) {
        if (e.key === "Enter" && !e.shiftKey) {
          e.preventDefault();
          sendMessage();
        }
      });

      function sendMessage() {
        const message = messageInput.value.trim();
        if (!message) return;

        // 检查interviewId是否存在
        if (!interviewId) {
          console.error("Interview ID is null or undefined");
          addMessage(
            "ai",
            "错误：面试ID不存在，请重新开始面试。如果问题持续存在，请联系管理员。"
          );
          return;
        }

        // 添加用户消息到聊天界面
        addMessage("user", message);
        messageInput.value = "";

        // 显示打字指示器
        showTypingIndicator();

        // 发送到服务器
        fetch("/api/chat/send", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            interviewId: interviewId,
            message: message,
          }),
        })
          .then((response) => response.json())
          .then((data) => {
            hideTypingIndicator();
            if (data.success) {
              if (data.aiResponse) {
                addMessage("ai", data.aiResponse);
              }
              if (data.interviewCompleted) {
                // 面试完成，重定向到结果页面
                setTimeout(() => {
                  window.location.href = "/result/" + interviewId;
                }, 2000);
              }
            } else {
              addMessage("ai", "抱歉，发生了错误：" + data.error);
            }
          })
          .catch((error) => {
            hideTypingIndicator();
            addMessage("ai", "抱歉，网络连接出现问题，请稍后重试。");
            console.error("Error:", error);
          });
      }

      // 修复后的完整 addMessage 函数
      function addMessage(sender, content) {
        const messageDiv = document.createElement("div");
        messageDiv.className = `message ${sender}`;

        const avatarDiv = document.createElement("div");
        avatarDiv.className = "message-avatar";
        avatarDiv.innerHTML =
          sender === "user"
            ? '<i class="bi bi-person"></i>'
            : '<i class="bi bi-robot"></i>';

        const contentDiv = document.createElement("div");
        contentDiv.className = "message-content";
        contentDiv.textContent = content;

        messageDiv.appendChild(avatarDiv);
        messageDiv.appendChild(contentDiv);

        chatContainer.appendChild(messageDiv);

        // 滚动到底部
        chatContainer.scrollTop = chatContainer.scrollHeight;
      }

      function showTypingIndicator() {
        typingIndicator.style.display = "flex";
        chatContainer.appendChild(typingIndicator);
        chatContainer.scrollTop = chatContainer.scrollHeight;
      }

      function hideTypingIndicator() {
        typingIndicator.style.display = "none";
      }

      function loadChatHistory() {
        if (!interviewId) return;

        fetch("/api/chat/history/" + interviewId)
          .then((response) => response.json())
          .then((data) => {
            if (data.success && data.messages) {
              data.messages.forEach((msg) => {
                addMessage(msg.sender, msg.content);
              });
            }
          })
          .catch((error) => {
            console.error("Failed to load chat history:", error);
            addMessage("ai", "加载聊天历史失败，请刷新页面重试。");
          });
      }
    </script>
  </body>
</html>
